from playwright.sync_api import sync_playwright
class PlayWriteAutomation:
    def __init__(self, headless=True):
        self.playwright = None
        self.browser = None
        self.context = None
        self.page = None
        self.headless = headless

        # 定义 HTTP 头，用于 requests 模拟浏览器请求
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Referer': 'https://www.baidu.com/'
        }

    def start_browser(self):
        if self.playwright is None:
            self.playwright = sync_playwright().start()
            # 监听所有请求
        self.browser = self.playwright.chromium.launch(
            headless=self.headless,
            args=[
                '--ignore-certificate-errors',
                '--disable-blink-features=AutomationControlled'
            ]
        )
        self.context = self.browser.new_context(
            user_agent=self.headers['User-Agent'],
            locale='zh-CN',
            ignore_https_errors=True  # 忽略 HTTPS 错误
        )
        self.page = self.context.new_page()
        print("浏览器已启动")

    def close_browser(self):
        if self.browser:
            self.browser.close()
        print("浏览器已关闭")

    def navigate_to_site(self, url):
        try:
            # 监听所有响应并获取状态码
            self.page.goto(url)

            # 等待页面加载完成，确保页面稳定
            try:
                self.page.wait_for_load_state("load")
                print("加载完成")
            except:
                pass

            return True
        except Exception as e:
            # 打印报错日志堆栈信息
            import traceback
            traceback.print_exc()
            print(f"访问 {url} 时出错: {e}")
            return False

    def click_about_button(self):
        try:
            # 使用按钮的类名来查找并点击
            self.page.click("button.VfPpkd-Bz112c-LgbsSe.yHy1rc.eT1oJ.QDwDD.mN1ivc.VxpoF")
            return True
        except Exception as e:
            import traceback
            traceback.print_exc()
            return False

    def wait_second(self, time):
        self.page.wait_for_timeout(time)

    def get_version_and_date_time(self):
        try:
            # 等待目标元素的加载
            self.page.wait_for_selector('div.q078ud:has-text("版本")')

            # 获取“版本”和“更新日期”的信息
            version_locator = self.page.locator('div.sMUprd:has(div.q078ud:has-text("版本")) div.reAt0')
            version = version_locator.first.inner_text() # 只获取第一个匹配项
            update_date = self.page.locator('div.sMUprd:has(div.q078ud:has-text("更新日期")) div.reAt0').inner_text()

            # 打印获取到的值
            print("版本:", version)
            print("更新日期:", update_date)
            return version, update_date
        except Exception as e:
            import traceback
            traceback.print_exc()
            return None, None

    def get_app_name(self):
        try:
            # 等待页面加载完成，确保所需元素可见
            self.page.wait_for_selector('span.AfwdI[itemprop="name"]')

            # 使用选择器提取应用名称
            app_name = self.page.locator('span.AfwdI[itemprop="name"]').inner_text()
            print(app_name)
            return app_name
        except Exception as e:
            import traceback
            traceback.print_exc()
            return None


# 创建 PlayWriteAutomation 实例，并启动爬虫
my_play_write_automation = PlayWriteAutomation(headless=False)